/**
 * Created by lmn98 on 2017/5/24.
 */
var fork = require('child_process').fork;
var db = require('./my_sequlize');
var ffmpegProcess = fork(__dirname+'/ffmpeg');
var ffmpeg = require('fluent-ffmpeg');
var works = {};

ffmpegProcess.on('message', function (msg) {
    if(msg.errormsg){
        db.transcode.update({
            state: 1 //0 start, 1 error, 2 finish
        },{
            where: { workNo: msg.workNo}
        })
    }else{
        db.transcode.update({
            state: 2 //0 start, 1 error, 2 finish
        },{
            where: { workNo: msg.workNo}
        })
    }
    delete works[msg.workNo];
});

module.exports = {
    metadata: function(filePath, callback){
        ffmpeg.ffprobe(filePath, function (e, data) {
            typeof callback === 'function' && callback(data, e);
        })
    },
    transcoding: function (workNo, size, aspect, start, end, filePath, savePath, callback) {
        ffmpegProcess.send({
            command: 1,
            size: size*1,
            aspect: aspect,
            start: start,
            end: end,
            filePath: filePath,
            savePath: savePath,
            workNo: workNo
        });
        if(callback) callback({
            workNo: workNo,
            queue: Object.keys(works).length
        });
        works[workNo] = 1;
    },
    screenShort: function (workNo, name, filePath, savePath, callback) {
        ffmpegProcess.send({
            command: 2,
            name: name,
            filePath: filePath,
            savePath: savePath,
            workNo: workNo
        });
        if(callback) callback({
            workNo: workNo,
            queue: Object.keys(works).length
        });
        works[workNo] = 1;
    },
    stopWork: function (workNo, callback) {
        if(works.hasOwnProperty(workNo)){
            ffmpegProcess.send({
                command: -1,
                workNo: workNo
            });
            db.transcode.update({
                state: 1
            },{
                where: {
                    workNo: workNo
                }
            })
        }
        callback()
    }
};